package cn.tannn.ops.customer.service.impl;

import cn.tannn.jdevelops.jpa.service.J2ServiceImpl;
import cn.tannn.jdevelops.result.utils.UUIDUtils;
import cn.tannn.ops.customer.constant.RoleStatus;
import cn.tannn.ops.customer.controller.dto.RoleAdd;
import cn.tannn.ops.customer.dao.RoleDao;
import cn.tannn.ops.customer.entity.Role;
import cn.tannn.ops.customer.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;


/**
 * 角色
 *
 * @author <a href="https://tannn.cn/">tan</a>
 * @date 2023/12/4 13:20
 */
@Service
public class RoleServiceImpl extends J2ServiceImpl<RoleDao, Role,Long> implements RoleService {

    public RoleServiceImpl() {
        super(Role.class);
    }

    @Override
    public boolean registerRole(RoleAdd authRole) {
        Role to = authRole.to(Role.class);
        if (verifyRoleExist(to.getCode(),to.getName())) {
            return false;
        } else {
            if (StringUtils.isBlank(to.getCode())) {
                to.setCode(UUIDUtils.getInstance().generateShortUuid());
            }
            to.setType(2);
            getJpaBasicsDao().saveAndFlush(to);
            return true;
        }
    }

    @Override
    public boolean verifyRoleExist(String code, String name) {
        Role role = new Role();
        role.setCode(code);
        role.setName(name);
        return getJpaBasicsDao().exists(Example.of(role));
    }

    @Override
    public boolean verifyRoleExist(String name) {
        return getJpaBasicsDao().existsByName(name);
    }

    @Override
    public void enable(List<String> codes) {
        getJpaBasicsDao().changeStatus(codes, RoleStatus.NORMAL.getStatus());
    }

    @Override
    public void disabled(List<String> codes) {
        getJpaBasicsDao().changeStatus(codes, RoleStatus.DISABLE.getStatus());
    }

    @Override
    public void deleteByCodes(List<String> codes) {
        getJpaBasicsDao().deleteByCodeInAndType(codes);
    }

    @Override
    public Optional<Role> findByCode(String code) {
        return getJpaBasicsDao().findByCode(code);
    }

    @Override
    public List<Role> findByCode(List<String> code) {
        return getJpaBasicsDao().findByCodeIn(code);
    }

    @Override
    public List<Role> findEnable() {
        return getJpaBasicsDao().findEnableRoles();
    }
}
